<?php
// +----------------------------------------------------------------------
// | [RhaPHP System] Copyright (c) 2017 http://www.rhaphp.com/
// +----------------------------------------------------------------------
// | [RhaPHP] 并不是自由软件,你可免费使用,未经许可不能去掉RhaPHP相关版权
// +----------------------------------------------------------------------
// | Author: Geeson <qimengkeji@vip.qq.com>
// +----------------------------------------------------------------------

namespace addons\nbforms\controller;


use app\common\controller\Addon;
use think\Db;
use think\facade\Env;
use think\facade\Request;

class Forms extends Addon
{
    public $adminLogin = true;
    public $theme = 'admin';

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        if (empty($this->getAaddonConfigByMp)) {
            $this->error('你还没有在管理后台进行“参数设置”');
        }
    }

    public function addForm()
    {
        if (Request::isAjax()) {
            $in = input('post.');
            $in['attribute_need'] = isset($in['attribute_need']) ? array_flip($in['attribute_need']) : [];
            $need = [];
            if (!empty($in['attribute_need'])) {
                foreach ($in['attribute_need'] as $key => $value) {
                    $need[$key - 1] = 1;
                }
            }
            if (!$in['picurl']) {
                ajaxMsg('0', '封面不能为空');
            }
            $data['mid'] = $this->mid;
            $data['title'] = trim($in['title']);
            $data['title2'] = trim($in['title2']);
            $data['keyword'] = trim($in['keyword']);
            $data['picurl'] = $in['picurl'];
            $data['content'] = $in['content'];
            $data['content2'] = $in['content2'];
            $data['jump_url'] = trim($in['jump_url']);
            $data['template'] = $in['template'];
            $data['success_msg'] = $in['success_msg'];
            $data['create_time'] = time();
            $attr = [];
            foreach ($in['attribute_sort'] as $key => $val) {
                $attr[$key] = [
                    'sotr' => $in['attribute_sort'][$key],
                    'name' => $in['attribute_name'][$key],
                    'type' => $in['attribute_type'][$key],
                    'values' => isset($in['attribute_values'][$key]) ? $in['attribute_values'][$key] : '',
                    'need' => isset($need[$key]) ? '1' : '0',
                    'defval' => $in['attribute_defval'][$key],
                    'tip' => $in['attribute_tip'][$key],
                    'regular' => $in['attribute_regular'][$key],
                    'regularMsg' => $in['attribute_regularMsg'][$key]
                ];
            }
            $data['attr_value'] = json_encode($attr);
            if ($id = Db::name('forms')->insertGetId($data)) {
                if ($reply_id = setMpKeywordByNews($data['keyword'], $data['title'], $data['picurl'], $data['content'], addonUrl('subfms/index', ['id' => $id]))) {
                    Db::name('forms')->where('id', $id)->update(['reply_id' => $reply_id]);
                    ajaxMsg(1, '操作成功');
                } else {
                    Db::name('forms')->where('id', $id)->delete();
                    ajaxMsg(0, '增加关键词失败');
                }
            } else {
                ajaxMsg(0, '增加失败');
            }
        } else {
            $theme = explode('|', $this->getAaddonConfigByMp['_theme']);
            $this->assign('theme', $theme);
            $this->fetch();
        }
    }


    public function lists()
    {
        $forms = Db::name('forms')->where('mid', $this->mid)->order('id DESC')->paginate(20);
        $page = $forms->render();
        $data = [];
        foreach ($forms as $key => $val) {
            $data[$key] = $val;
            if (isset($forms[$key]['attr_value'])) {
                $data[$key]['attr_value'] = json_decode($val['attr_value'], true);
            }
        }
        $this->assign('page', $page);
        $this->assign('data', $data);
        return $this->fetch();
    }


    public function edit()
    {
        $id = input('id');
        $forms = Db::name('forms')->where(['mid' => $this->mid, 'id' => $id])->find();
        $attr = json_decode($forms['attr_value'], true);
        $forms['attr_value'] = [];
        foreach ($attr as $key => $val) {
            $forms['attr_value'][$key] = $val;
//            if($val['type']==3 || $val['type']==4 ||$val['type']==5 ){
//                $valArr = preg_replace("/(\n)|(\s)|(\t)|(\')|(')|(，)/", ',', $val['values']);
//                $array=explode(",", $valArr);
//                if(isset($array[0]) && empty($array[0])){
//                    $forms['attr_value'][$key]['values'] =[];
//                }else{
//                    $forms['attr_value'][$key]['values'] = $array;
//                }
//
//            }
        }
        if (Request::isAjax()) {
            $in = input('post.');
            //$in['attribute_need'] = isset($in['attribute_need']) ? array_flip($in['attribute_need']) : [];
            $need = $in['attribute_need'];
            if (!$in['picurl']) {
                ajaxMsg('0', '封面不能为空');
            }
            $data['mid'] = $this->mid;
            $data['title'] = trim($in['title']);
            $data['title2'] = trim($in['title2']);
            $data['keyword'] = trim($in['keyword']);
            $data['picurl'] = $in['picurl'];
            $data['content'] = $in['content'];
            $data['content2'] = $in['content2'];
            $data['jump_url'] = $in['jump_url'];
            $data['template'] = $in['template'];
            $data['success_msg'] = $in['success_msg'];
            $data['create_time'] = time();
            $attr = [];
            foreach ($in['attribute_sort'] as $key => $val) {
                $attr[$key] = [
                    'sotr' => $in['attribute_sort'][$key],
                    'name' => $in['attribute_name'][$key],
                    'type' => $in['attribute_type'][$key],
                    'values' => isset($in['attribute_values'][$key]) ? $in['attribute_values'][$key] : '',
                    'need' => isset($need[$key]) ? '1' : '0',
                    'defval' => $in['attribute_defval'][$key],
                    'tip' => $in['attribute_tip'][$key],
                    'regular' => $in['attribute_regular'][$key],
                    'regularMsg' => $in['attribute_regularMsg'][$key]
                ];
            }
            $data['attr_value'] = json_encode($attr);
            if ($id = Db::name('forms')->where(['mid' => $this->mid, 'id' => input('id')])->update($data)) {
                if ($reply_id = setMpKeywordByNews($data['keyword'], $data['title'], $data['picurl'], $data['content'], addonUrl('subfms/index', ['id' => input('id')]))) {
                    ajaxMsg(1, '修改成功');
                } else {
                    ajaxMsg(0, '修改失败');
                }
            } else {
                ajaxMsg(0, '修改失败');
            }
        } else {
            $theme = explode('|', $this->getAaddonConfigByMp['_theme']);
            $this->assign('theme', $theme);
            $this->assign('form', $forms);
            $this->fetch();
        }
    }

    public function getData()
    {
        $db = Db::name('forms_values');
        if (!empty($content = input('content'))) {
            $db->where('a.val', 'like', '%' . $content . '%');
        }
        if (!empty($time = input('time'))) {
            $times = explode('~', $time);
            $db->where('a.create_time', 'between', [strtotime($times[0]), strtotime($times[1])]);
        }
        $status = input('status');
        if (is_numeric($status) && $status != -1) {
            $db->where('a.status', $status);
        } else {
            $status = -1;
        }
        $data = $db
            ->alias('a')
            ->where(['a.mid' => $this->mid, 'a.forms_id' => input('id')])
            ->join('__FORMS__ b', 'b.id=a.forms_id')
            ->field('a.*,b.attr_value')
            ->order('id DESC')
            ->paginate(20);
        $data2 = [];
        foreach ($data as $key => $val) {
            $data2[$key] = $val;
            if ($val['val']) {
                $data2[$key]['val'] = json_decode($val['val'], true);
                foreach ($data2[$key]['val'] as $k => $v) {
                    if (is_array($data2[$key]['val'][$k])) {
                        array_pop($data2[$key]['val'][$k]);
                        $data2[$key]['val'][$k] = implode(',', $data2[$key]['val'][$k]);
                    } else {
                        if ($this->isImage($data2[$key]['val'][$k])) {
                            $data2[$key]['val'][$k] = '<a target="_blank" href="' . $v . '"><img class="form-image" src="' . $v . '"/></a>';
                        }
                    }
                }
            }
            if ($val['attr_value']) {
                $data2[$key]['attr_value'] = json_decode($val['attr_value'], true);
            }
        }
        $data3 = [];
        $dataTitle = [];
        foreach ($data2 as $key => $val) {
            foreach ($val['attr_value'] as $key1 => $val2) {
                if (array_key_exists($val2['name'], $val['val'])) {
                    $data3[$key][$val2['name']] = $val['val'][$val2['name']];
                    $dataTitle[$key][$val2['name']] = $val['val'][$val2['name']];
                } else {
                    $data3[$key][$val2['name']] = '';
                    $dataTitle[$key][$val2['name']] = '';
                }
            }
            $dataTitle[$key]['创建时间'] = '';
            $dataTitle[$key]['标记?'] = '';
            $dataTitle[$key]['操作'] = '';
            $data3[$key]['创建时间'] = date('y-m-d,H:i', $val['create_time']);
            $data3[$key]['标记?'] = $val['status'] == 1 ? '已标记' : '未标记';
            $data3[$key]['操作'] = "<a onclick=\"delFormsData('{$val['id']}')\" class=\"rha-bt-a\" href=\"javascript:;\">删除</a>
<a onclick=\"setFormStatus('{$val['id']}','{$val['status']}')\" class=\"rha-bt-a\" href=\"javascript:;\">标记</a>";
        }
        $Title = [];
        if (isset($dataTitle[0])) {
            $Title = $dataTitle[0];
        }
        $this->assign('page', $data->render());
        $this->assign('data', $data3);
        $this->assign('dataTitle', $Title);
        $this->assign('status', $status);
        $this->fetch();
    }

    public function isImage($url)
    {
        $type = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'JPG', 'PNG', 'JPEG', 'GIF', 'BMP'];
        foreach ($type as $val) {
            if (strpos($url, $val)) {
                return true;
            }
        }
    }


    public function setFormStatus()
    {
        if (Request::isAjax()) {
            $status = input('val');
            $status == 1 ? $status = 0 : $status = 1;
            if (Db::name('forms_values')->where(['mid' => $this->mid, 'id' => input('fid')])->update(['status' => $status])) {
                ajaxMsg(1, '标记成功');
            } else {
                ajaxMsg(1, '标记失败');
            }
        }
    }

    public function delFormsData()
    {
        if (Request::isAjax()) {
            if (Db::name('forms_values')->where(['mid' => $this->mid, 'id' => input('fid')])->delete()) {
                ajaxMsg(1, '删除成功');
            } else {
                ajaxMsg(1, '操作失败');
            }
        }
    }


    public function delForms()
    {
        if (Request::isAjax()) {
            $result = Db::name('forms')->where(['mid' => $this->mid, 'id' => input('fid')])->find();
            if (!empty($result)) {
                delKeywordReply($result['reply_id']);
                Db::name('forms')->where(['mid' => $this->mid, 'id' => input('fid')])->delete();
                Db::name('forms_values')->where(['mid' => $this->mid, 'forms_id' => input('fid')])->delete();
                ajaxMsg(1, '删除成功');
            } else {
                ajaxMsg(0, '没有删除的内容');
            }
        }
    }

    public function export()
    {
        $data = Db::name('forms_values')
            ->alias('a')
            ->where(['a.mid' => $this->mid, 'a.forms_id' => input('id')])
            ->join('__FORMS__ b', 'b.id=a.forms_id')
            ->field('a.*,b.attr_value,b.title')
            ->order('id DESC')
            ->select();
        $data2 = [];
        foreach ($data as $key => $val) {
            $data2[$key] = $val;
            if ($val['val']) {
                $data2[$key]['val'] = json_decode($val['val'], true);
                foreach ($data2[$key]['val'] as $k => $v) {
                    if (is_array($data2[$key]['val'][$k])) {
                        array_pop($data2[$key]['val'][$k]);
                        $data2[$key]['val'][$k] = implode(',', $data2[$key]['val'][$k]);
                    } else {
                        if ($this->isImage($data2[$key]['val'][$k])) {
                            $data2[$key]['val'][$k] = $v;
                        }
                    }
                }
            }
            if ($val['attr_value']) {
                $data2[$key]['attr_value'] = json_decode($val['attr_value'], true);
            }
        }
        $data3 = [];
        $dataTitle = [];
        foreach ($data2 as $key => $val) {
            foreach ($val['attr_value'] as $key1 => $val2) {
                if (array_key_exists($val2['name'], $val['val'])) {
                    $data3[$key][$val2['name']] = $val['val'][$val2['name']];
                    $dataTitle[$key][$val2['name']] = $val['val'][$val2['name']];
                } else {
                    $data3[$key][$val2['name']] = '';
                    $dataTitle[$key][$val2['name']] = '';
                }
            }
            $dataTitle[$key]['创建时间'] = '';
            $dataTitle[$key]['操作'] = '';
            $data3[$key]['创建时间'] = date('y-m-d,H:i', $val['create_time']);
        }
        pr($this->addonRoot);
        include_once $this->addonRoot . 'extend/PHPExcel/Classes/PHPExcel.php';
        $objPHPExcel = new \PHPExcel();
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $objActSheet = $objPHPExcel->getActiveSheet();
        if (isset($data3[0]) && is_array($data3[0]) && !empty($data3[0])) {
            $i = 0;
            foreach ($data3[0] as $key => $field) {
                $tableField = \PHPExcel_Cell::stringFromColumnIndex($i);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tableField . '1', $key);
                $i++;
            }
            $j = 2;
            foreach ($data3 as $key => $value) {
                $i = 0;
                foreach ($value as $key1 => $value1) {
                    $tableField = \PHPExcel_Cell::stringFromColumnIndex($i);
                    if ($this->isImage($value1)) {
                        $objDrawing = new \PHPExcel_Worksheet_Drawing ();
                        $array_imag = explode('uploads', $value1);
                        if (is_array($array_imag) && !empty($array_imag)) {
                            $img_file = Env::get('root_path') . 'uploads' . $array_imag[1];
                            if (is_file($img_file)) {
                                $objDrawing->setPath($img_file);
                                $objDrawing->setHeight(80);//照片高度
                                // $objDrawing->setWidth(); //照片宽度
                                $objDrawing->setCoordinates($tableField . $j);
                                $objDrawing->setOffsetX(5);
                                $objDrawing->setOffsetY(5);
                                $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
                                $objActSheet->getRowDimension($j)->setRowHeight(80);
                            } else {
                                $objActSheet->setCellValue($tableField . $j, '图片路径不存在');
                            }
                        } else {
                            $objActSheet->setCellValue($tableField . $j, $value1);
                        }
                    } else {
                        $objActSheet->setCellValue($tableField . $j, $value1);
                    }
                    $i++;
                }
                $j++;
            }
            $fileName = '二哈系统-万能表单-' . $data[0]['title'] . '.xlsx';
            $objPHPExcel->getActiveSheet()->setTitle($fileName);
            $objPHPExcel->setActiveSheetIndex(0);
            ob_end_clean();//清除缓冲区,避免乱码
            header('Content-Type: application/vnd.ms-excel');
            header("Content-Disposition: attachment;filename=\"$fileName\"");
            header('Cache-Control: max-age=0');
            $objWriter->save('php://output'); //文件通过浏览器下载

        }
    }

}